import axios from 'axios'

import { useUserStore } from '@/stores/index'
const baseURL =
  // eslint-disable-next-line no-undef
  process.env.NODE_ENV === 'development' ? 'http://192.168.124.9:9000' : 'http://1.94.27.34:9000'
const request = axios.create({
  baseURL: baseURL,
  timeout: 20000
})

//请求拦截器
request.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    return config
  },
  (err) => Promise.reject(err)
)
// 响应拦截器
request.interceptors.response.use(
  (response) => {
    let res = response.data
    if (typeof res === 'string') {
      res = res ? JSON.parse(res) : res
    }
    return res
  },
  (error) => {
    console.log('err' + error)
    return Promise.reject(error)
  }
)

export default request
export { baseURL }
